#!/usr/bin/env node

/**
* Module dependencies.
*/

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var express = require('express');

var app = express();
var debug = require('debug')('myapp-express:server');
var http = require('http');
var helloRouter = require('./routes/hello');
app.use('/hello', helloRouter);

module.exports = app;
if (cluster.isMaster) {
    var numWorkers = require('os').cpus().length;
    console.log('Master cluster setting up ' + numWorkers + ' workers...');
    for(var i = 0; i < numWorkers; i++) {
        cluster.fork();
    }
    cluster.on('online', function(worker) {
        console.log('Worker ' + worker.process.pid + ' is online');
    });
    cluster.on('exit', function(worker, code, signal) {
        console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
        console.log('Starting a new worker');
        cluster.fork();
    });
    /**
    console.log('[master] ' + "start master...");
    for (var i = 0; i < numCPUs+4; i++) {
        cluster.fork();
    }

    cluster.on('listening', function (worker, address) {
        console.log('[master] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
    });
    */
} else if (cluster.isWorker) {
    console.log('[worker] ' + "start worker ..." + cluster.worker.id);
    http.createServer(app).listen(8080);
/*
http.createServer(app) {
console.log('worker'+cluster.worker.id);
res.end('worker'+cluster.worker.id+',PID:'+process.pid);

}).listen(3000);*/
}